const express = require('express')
const router = express.Router()
const Advert = require('../models').Advert
const config = require('../config')
const pFormidable = require('../utility/formidable')

// get all
// query { pageSize, pageNumber }
router.get('/adverts', (req, res, next) => {
  let { pageSize, pageNumber } = req.query
  pageNumber = Number.parseInt(pageNumber, 10)
  pageSize = Number.parseInt(pageSize, 10)
  const result = {}
  Advert.find().skip((pageNumber - 1) * pageSize).limit(pageSize)
    .then(docs => {
      result.list = docs
      return Advert.count()
    })
    .then(count => {
      result.count = count
      res.json({
        success: true,
        ret: result
      })
    })
    .catch(err => {
      next(err)
    })
})

// add
router.post('/adverts', (req, res, next) => {
  const body = req.body
  pFormidable(req, config.uploadDir)
    .then((fields) => {
      const advert = new Advert({
        ad_image: fields.image,
        ad_title: fields.title,
        ad_link: fields.link,
        ad_start_time: new Date(fields.start_time).getTime(),
        ad_end_time: new Date(fields.end_time).getTime(),
        ad_available: fields.available === 'false' ? false: true,
      })
      return advert.save()
    })
    .then(() => {
      res.json({
        success: true,
        ret: {}
      })
    })
    .catch(err => {
      next(err)
    })
})

// findById
router.get('/adverts/:id', (req, res, next) => {
  Advert.findById(req.params.id)
    .then(doc => {
      res.json({
        success: true,
        ret: {
          data: docs[0] || {}
        }
      })
    })
    .catch(err => {
      next(err)
    })
})

// 更新所有字段（需要客户端提供完整信息数据）
router.put('/adverts/:id', (req, res, next) => {
  Advert.findById(req.params.id)
    .then(doc => {
      doc.ad_image = req.body.ad_image
      doc.ad_title = req.body.ad_title
      doc.ad_link = req.body.ad_link
      doc.ad_start_time = req.body.ad_start_time
      doc.ad_end_time = req.body.ad_end_time
      doc.ad_available = req.body.ad_available
      return doc.save()
    })
    .then(() => {
      res.json({
        success: true,
        ret: {}
      })
    })
    .catch(err => {
      next(err)
    })
})

// 删除
router.delete('/adverts/:id', (req, res, next) => {
  Advert.findByIdAndRemove(req.params.id)
    .then(() => {
      res.json({
        success: true,
        ret: {}
      })
    })
    .catch(err => {
      next(err)
    })
})

module.exports = router
